package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.AtMessage;
import com.kaishengit.entity.Message;
import com.kaishengit.entity.Project;
import com.kaishengit.entity.User;
import com.kaishengit.entity.UserProject;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.Page;
import com.kaishengit.util.RowMapper;

public class MessageDao {
	private DBHelp<Message> db=new DBHelp<Message>();
	
	public void save(Message m) {
		final String sql="INSERT INTO t_message(id,content,createtime,t_project_id,t_user_id)VALUES(?,?,?,?,?)";
		db.executeSQL(sql, m.getId(),m.getContent(),m.getCreatetime(),m.getProjectId(),m.getUserId());
	}
	public List<Message> findMessage(UserProject userProject) {
		StringBuilder sql=new StringBuilder();
		sql.append("SELECT tm.id,tm.content,tm.createtime,tm.t_project_id,tm.t_user_id,tu.`name` AS username,tu.password,tu.pic,tp.`name`,tp.`desc`,tp.createtime AS ctime FROM t_message AS tm ");
		sql.append("LEFT JOIN t_user AS tu ON tu.id=tm.t_user_id ");
		sql.append("LEFT JOIN t_project AS tp ON tp.id=tm.t_project_id ");
		sql.append("WHERE tm.t_project_id= ?");
		return db.executeQueryForList(sql.toString(),new MessageRowMapper(),userProject.getProjectId());
	}
	private class MessageRowMapper implements RowMapper<Message>{
		public Message mapperRow(ResultSet rs) throws SQLException {
			Message m=new Message();
			m.setId(rs.getString("id"));
			m.setContent(rs.getString("content"));
			m.setCreatetime(rs.getString("createtime"));
			m.setStringtime(rs.getString("createtime"));
			
			User u=new User();
			u.setName(rs.getString("username"));
			u.setPassword(rs.getString("password"));
			u.setPic(rs.getString("pic"));
			m.setUser(u);
			m.setUserId(rs.getString("t_user_id"));
			
			Project p=new Project();
			p.setName(rs.getString("name"));
			p.setDesc(rs.getString("desc"));
			p.setCreatetime(rs.getString("ctime"));
			m.setProject(p);
			m.setProjectId(rs.getString("t_project_id"));
			return m;
		}
	}
}
	


